package com.zhj.edu.iotserver.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.zhj.edu.exception.handler.BusinessException;
import com.zhj.edu.pojo.Tenant;
import com.zhj.edu.iotserver.mapper.TenantMapper;
import com.zhj.edu.iotserver.service.TenantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhj.edu.result.ResponseCode;
import com.zhj.edu.utils.SnowflakeIdGenerator;
import com.zhj.edu.vo.TenantAuditVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * <p>
 * 租户表 服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2024-09-13
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(Tenant tenant) {
        //首先校验参数的合法性
        if (null==tenant || StringUtils.isEmpty(tenant.getName()) || StringUtils.isEmpty(tenant.getPwd()) || StringUtils.isEmpty(tenant.getCompanyName()) || StringUtils.isEmpty(tenant.getCompanyCode()) || StringUtils.isEmpty(tenant.getDescription()) || StringUtils.isEmpty(tenant.getPhone())){
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(), ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
        //执行到这里说明参数无误，就能添加租户的信息了
        //在此之前需要先设置一些租户的信息
        tenant.setEnable(1);
        //生成租户的key，使用UUID生成,为了防止生成的key出现问题，所以加锁
        synchronized (this){
            long key = new SnowflakeIdGenerator(1, 1).nextId();
            tenant.setAccessKey(String.valueOf(key));
            tenant.setAccessSecurit(UUID.randomUUID().toString().replace("-","").trim());
        }

        tenantMapper.insert(tenant);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void audit(TenantAuditVo tenantAuditVo) {
        if (null==tenantAuditVo || StringUtils.isEmpty(tenantAuditVo.getTenantId()) || null==tenantAuditVo.getAuditStatus()){
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(), ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
        //执行到此处说明有数据
        //首先在这里进行查询
        Tenant tenant = tenantMapper.selectById(tenantAuditVo.getTenantId());
        if (null==tenant){
            throw new BusinessException(ResponseCode.TENANT_ID_EXCEPTION.getCode(), ResponseCode.TENANT_ID_EXCEPTION.getMsg());
        }
        tenant.setAuditStatus(tenantAuditVo.getAuditStatus());
        //执行到这里说明参数无误 直接更新
        tenantMapper.updateById(tenant);
    }


}
